package com.kim.rssreader.activity;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.client.RestTemplate;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeed;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeedImpl;
import com.kim.rssreader.R;
import com.kim.rssreader.adapter.SyndFeedListAdapter;
import com.kim.rssreader.utils.ActivityDispatchUtil;
import com.kim.rssreader.utils.NetUtil;
import com.kim.rssreader.utils.RSSTempleUtil;
import com.kim.rssreader.utils.RssMessageConstant;

public class RSSContentListActivity extends BaseActivity implements
		View.OnClickListener {

	public static final String TAG = "RSSContentListActivity";

	private ImageView mBack; // 返回按钮
	private ImageView mRefresh; // 刷新按钮
	private TextView mTitle; // 标题

	private ListView mRssContentListView;// 内容列表

	private String columnId; // 栏目id
	private String columnUrl; // 栏目url
	private String columnName; // 栏目名称
	private String columnCategory; // 栏目类别

	private String columnFlagStarter = null;
	private String columnFlagEnd = null;

	private SyndFeed feed;
	private SyndFeedListAdapter syndFeedListAdapter;

	List<SyndEntry> entriesLocal = null;

	private boolean fetchFlag = false;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case RssMessageConstant.MESSAGE_CONTENT_LIST_FETCH_COMPLETE:
				showLocalContentList();
				break;
			case RssMessageConstant.MESSAGE_START_ANIMATION:
				// start animation
				startRefreshAnim();
				break;
			case RssMessageConstant.MESSAGE_STOP_ANIMATION:
				// stop animation
				stopRefreshAnim();
				break;

			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void initView() {
		setContentView(R.layout.rss_content_list_view);
		mBack = (ImageView) findViewById(R.id.iv_back);
		mRefresh = (ImageView) findViewById(R.id.iv_refresh);

		mBack.setOnClickListener(this);
		mRefresh.setOnClickListener(this);

		mTitle = (TextView) findViewById(R.id.tv_columnTitle);
		mRssContentListView = (ListView) findViewById(R.id.lv_rss_content_list);

		mRssContentListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (feed == null) {
					return;
				}

				SyndEntry entry = (SyndEntry) feed.getEntries().get(position);
				ActivityDispatchUtil.toContentPage(RSSContentListActivity.this,
						entry, columnCategory, columnFlagStarter,
						columnFlagEnd, columnId);
			}
		});

		setTitle();
	}

	@Override
	protected void onResume() {
		super.onResume();
		showLocalContentList();
		if (!fetchFlag) {
			fetchContentList();
		}
	}

	@Override
	public void initParam() {
		Intent intent = getIntent();
		columnId = intent.getStringExtra("columnid");
		columnUrl = intent.getStringExtra("url");
		columnName = intent.getStringExtra("value");
		columnCategory = intent.getStringExtra("category");
		columnFlagStarter = intent.getStringExtra("flagStart");
		columnFlagEnd = intent.getStringExtra("flagEnd");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.iv_refresh:
			fetchContentList();
			break;
		}
	}

	private void setTitle() {
		if (mTitle == null) {
			return;
		}
		if (columnName == null || "".equals(columnName)) {
			return;
		}
		mTitle.setText(columnName);
	}

	private void refreshContentList() {
		if (feed == null) {
			return;
		}
		syndFeedListAdapter = (SyndFeedListAdapter) mRssContentListView
				.getAdapter();
		if (syndFeedListAdapter == null) {
			syndFeedListAdapter = new SyndFeedListAdapter(this, feed, dbDAO);
			mRssContentListView.setAdapter(syndFeedListAdapter);
		} else {
			syndFeedListAdapter.resetData(feed);
		}
		syndFeedListAdapter.notifyDataSetChanged();
	}

	private void fetchContentList() {

		// check the net
		if (!NetUtil.isNetAvailable(this)) {
			Toast.makeText(this, R.string.net_not_available, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		// start fetch content list
		new Thread(new Runnable() {

			@SuppressWarnings("unchecked")
			@Override
			public void run() {
				handler.sendEmptyMessage(RssMessageConstant.MESSAGE_START_ANIMATION);
				// Create a new RestTemplate instance
				RestTemplate restTemplate = RSSTempleUtil.getRestTemplate();
				try {
					// Initiate the request and return the results
					feed = restTemplate.getForObject(columnUrl, SyndFeed.class);
					List<SyndEntry> entries = new ArrayList<SyndEntry>();
					entries.addAll(feed.getEntries());
					dbDAO.insertColumnItemList(entries, entriesLocal, columnId);
					entries = null;
					fetchFlag = true;
					handler.sendEmptyMessage(RssMessageConstant.MESSAGE_CONTENT_LIST_FETCH_COMPLETE);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					handler.sendEmptyMessage(RssMessageConstant.MESSAGE_STOP_ANIMATION);
					restTemplate = null;
				}
			}
		}).start();

	}

	private void readContentListLocal() {
		entriesLocal = dbDAO.getColumnItemByColumnId(columnId);
	}

	private void showLocalContentList() {
		readContentListLocal();
		if (entriesLocal == null || entriesLocal.size() == 0) {
			return;
		}
		if (feed == null) {
			feed = new SyndFeedImpl();
		}
		feed.setEntries(entriesLocal);
		refreshContentList();
	}

	/**
	 * 开始刷新动画
	 */
	private void startRefreshAnim() {
		Log.i(TAG, "start animation");
		Animation animation = AnimationUtils.loadAnimation(this,
				R.anim.refresh_anim);
		mRefresh.setAnimation(animation);
		animation.start();
	}

	/**
	 * 结束刷新动画
	 */
	private void stopRefreshAnim() {
		Log.i(TAG, "stop animation");
		Animation animation = mRefresh.getAnimation();
		if (animation != null) {
			animation.cancel();
			animation = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (entriesLocal != null) {
			entriesLocal.clear();
			entriesLocal = null;
		}
	}

}
